package com.xg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xg.common.result.ApiResult;
import com.xg.common.util.RedisKeyUtils;
import com.xg.entity.User;
import com.xg.mapper.UserMapper;
import com.xg.remote.ThirdFeignClient;
import com.xg.remote.VerificationCodeFeignClient;
import com.xg.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    VerificationCodeFeignClient verificationCodeFeignClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdFeignClient thirdFeignClient;

    @Autowired
    UserMapper userMapper;

    /**
     * 发送验证码
     */
    @Override
    public String sendCode(String userPhone) {

        // 查询是否存在用户
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("user_phone", userPhone));
        if (count == 0){
            // 用户不存在
            return "0";
        }

        // 获取验证码
        ApiResult<String> verificationCode = verificationCodeFeignClient.getVerificationCode(6);
        String code = verificationCode.getData();

        // redis缓存验证码
        String userKey = RedisKeyUtils.USER_LOGIN_PREFIX+userPhone+"_";
        stringRedisTemplate.opsForValue().set(userKey,code,2, TimeUnit.MINUTES);

        // 发送验证码
//        thirdFeignClient.sendSmsCode(userPhone,code);

        return "1";
    }
}
